<template>
  <div class="ver-layout">
    <!-- 图表 -->
    <div id="mainCharts" style="width: calc(100vw - 200px);height: 350px"></div>
    <!--表格-->
    <el-table :data="tableComputedData.tableData" height="300px" border size="small"
              highlight-current-row :cell-style="cellStyle" :header-cell-style="headerCellStyle"
              @cell-click="cellClick"
              @header-click="headerClick">
      <el-table-column v-for="(headerItem,headerIndex) in tableComputedData.tableHeader"
                       :prop="headerItem"
                       :label="headerItem"
                       :show-overflow-tooltip="true"/>
    </el-table>
  </div>
</template>

<script setup lang="ts">
import * as echarts from "echarts";
import {computed, onMounted, reactive} from "vue";
import {dayOffType} from "@/utils/data_utils.ts";

interface Props {
  parentPageData?: Object;//
}

const props = withDefaults(defineProps<Props>(), {});

const pageData = reactive({
  pageLevelPre: 1,
  pageLevel: 1,
  tableData1: [],
  tableHeader1: [],
  tableData2: [],
  tableHeader2: [],
  tableData3: [],
  tableHeader3: [],
  options1: {},
  options2: {},
  myChart: '',
  chartSeriesData: '',
  selectColumn: ''
})
//动态的表格数据
const tableComputedData = computed(() => {
  let tableData = {
    1: pageData.tableData1,
    2: pageData.tableData2,
    3: pageData.tableData3
  }[pageData.pageLevel]
  let tableHeader = {
    1: pageData.tableHeader1,
    2: pageData.tableHeader2,
    3: pageData.tableHeader3
  }[pageData.pageLevel]
  return {
    tableData: tableData,
    tableHeader: tableHeader,
  }
})

//单元格样式
const cellStyle = (data) => {
  // console.log("cellStyle", data)
  let dayOffKey = tableComputedData.value.tableHeader.length > data.columnIndex && tableComputedData.value.tableHeader[data.columnIndex]
  let cellValue = data.row[dayOffKey]
  if (data.columnIndex > 0 && [1, 2].includes(pageData.pageLevel)) {
    return {
      color: cellValue != '-' ? dayOffType[dayOffKey] : '',
      textDecoration: cellValue != '-' ? 'underline' : '',
      paddingRight: cellValue != '-' ? '10px' : "",
    }
  }
  return {}
}

//单元格点击事件
const cellClick = (row, column) => {
  console.log("cellClick", row, column)
  if (row[column.label] && row[column.label] == '-') return
  if (column.label == '天') return;
  let eventData = {groupId1: row['天'], groupId2: column.label}
  let subData = pageData.chartSeriesData.find(item => item.dataGroupId === eventData.groupId1)
  console.log("subData==", subData)
  //三级页面
  if (eventData.groupId2) {
    subData = subData[eventData.groupId2]
    genTable3Data(subData, eventData)
    pageData.myChart.clear();
    pageData.myChart.setOption(genChartOptions3({subData, eventData}));
  }
}

//表头单元格样式
const headerCellStyle = (data) => {
  let dayOffKey = tableComputedData.value.tableHeader[pageData.selectColumn]
  if (pageData.pageLevel == 1 && pageData.selectColumn == data.columnIndex) {
    return {color: dayOffType[dayOffKey]}
  }
}

//表头单元格点击事件
const headerClick = (column) => {
  console.log("headerClick", column)
  if (pageData.pageLevel !== 1) return
  pageData.tableData1.sort((a, b) => a.index - b.index)
  if (pageData.selectColumn !== column.no) {
    pageData.tableData1.sort((a, b) => {
      let aValue = a[column.label] == '-' ? 0 : 1
      let bValue = b[column.label] == '-' ? 0 : 1
      return bValue - aValue;
    })
  }
  pageData.selectColumn = pageData.selectColumn == column.no ? '' : column.no
}

//初始化图表数据
const initChartData = () => {
  let tableData = JSON.parse(JSON.stringify(props.parentPageData.tableData))
  let xAxisData = JSON.parse(JSON.stringify(props.parentPageData.tableHeader)).filter(item => item.includes("日"))
  let totalSeries = {}
  let chartSeriesData = xAxisData.map(dayName => {
    let dayData = {}
    dayData.dataGroupId = dayName
    tableData.forEach(userItem => {
      let dayOff = userItem[dayName]
      if (!dayData[dayOff]) dayData[dayOff] = {data: [], value: 0}
      dayData[dayOff].value = dayData[dayOff].value + 1
      dayData[dayOff].data.push(userItem)
      totalSeries[dayOff] = dayOff
    })
    return dayData
  })
  let seriesData = Object.keys(totalSeries).map((name, sid) => {
    return {
      name,
      type: "bar",
      stack: 'total',
      barWidth: '60%',
      label: {
        show: true,
        fontSize: 10,
        formatter: (params) => params.data.value ? params.data.value : '',
      },
      data: chartSeriesData.map(item => {
        return {
          value: item[name] && item[name].value ? item[name].value : 0,
          groupId1: item.dataGroupId,
          groupId2: name
        }
      })
    }
  })
  // console.log("totalSeries==", totalSeries)
  // console.log("chartSeriesData==", chartSeriesData)
  // console.log("seriesData==", seriesData)
  pageData.tableHeader1 = seriesData.map(item => item.name)
  pageData.tableHeader1.unshift("天")
  pageData.tableData1 = chartSeriesData.map((item, index) => {
    let data = {}, keyList = pageData.tableHeader1
    keyList.forEach(key => data[key] = item[key] && item[key].value ? item[key].value : '-')
    data['天'] = item.dataGroupId
    data.index = index
    return data
  })
  // console.log("pageData.tableData==", pageData.tableData1)
  return {xAxisData, totalSeries, chartSeriesData, seriesData}
}

//生成图表1的配置项
const genChartOptions1 = ({xAxisData, totalSeries, seriesData}) => {
  let dayOffTypeList = Object.keys(dayOffType)
  return {
    grid: {
      // top: 10,
      left: 100,
      right: 100,
      // bottom: 20,
    },
    title: {
      text: `${props.parentPageData.monthValue}月考勤数据`
    },
    color: Object.keys(totalSeries).map(item => {
      let key = dayOffTypeList.find(dayItem => dayItem.includes(item))
      return dayOffType[key]
    }),
    legend: {
      data: Object.keys(totalSeries),
      formatter: (params) => params,
    },
    xAxis: {
      data: xAxisData,
      axisLabel: {
        // 强制显示所有标签
        interval: 0,
      },
    },
    yAxis: {},
    dataGroupId: '',
    animationDurationUpdate: 500,
    series: seriesData,
    graphic: []
  }
}

//生成表格2的数据
const genTable2Data = (subData) => {
  //第一种展示形式
  // let tableData2 = []
  // pageData.pageLevel = 2
  // pageData.tableHeader2 = Object.keys(subData).filter(item => item != 'dataGroupId')
  // pageData.tableHeader2.unshift("序号", "员工编号")
  // pageData.tableHeader2.forEach(headerItem => {
  //   let userNameList = subData[headerItem] && subData[headerItem].data.map(item => {
  //     return {
  //       [headerItem]: item['员工姓名'],
  //       '员工编号': item['员工编号']
  //     }
  //   })
  //   userNameList = userNameList ? userNameList : []
  //   tableData2 = [...tableData2, ...userNameList]
  // })
  // tableData2 = tableData2.map((item, index) => {
  //   item["序号"] = index + 1
  //   return item
  // })
  // pageData.tableData2 = tableData2

  //第二种展示形式
  let tableDataObj2 = {}
  pageData.pageLevel = 2
  pageData.tableHeader2 = Object.keys(subData).filter(item => item != 'dataGroupId')
  pageData.tableHeader2.unshift("天")
  pageData.tableHeader2.forEach(headerItem => {
    if (headerItem != '天') tableDataObj2[headerItem] = subData[headerItem].data.length
    else tableDataObj2[headerItem] = subData['dataGroupId']
  })
  pageData.tableData2 = [tableDataObj2]
}

//生成图表2详情的配置项
const genChartOptions2 = ({myChart, subData, options1}) => {
  let dayOffTypeList = Object.keys(dayOffType)
  let seriesData = Object.keys(subData).filter(item => item != 'dataGroupId')
  seriesData = seriesData.map((key, index) => {
    let newSeriesDataArr = Array.from({length: seriesData.length}, (v, i) => {
      return {
        groupId1: subData.dataGroupId,
        groupId2: key,
        value: 0
      }
    })
    newSeriesDataArr[index].value = subData[key].value
    return {
      name: key,
      type: "bar",
      stack: 'total',
      barWidth: '70',
      label: {
        show: true,
        fontSize: 10,
        formatter: (params) => params.value ? params.value : '',
      },
      data: newSeriesDataArr,
      dataGroupId: subData.dataGroupId,
      universalTransition: {
        enabled: true,
        divideShape: 'clone'
      }
    }
  })
  return {
    title: {
      text: `${props.parentPageData.monthValue}月${subData.dataGroupId}考勤数据`
    },
    color: Object.keys(subData).filter(item => item != 'dataGroupId').map(item => {
      let key = dayOffTypeList.find(dayItem => dayItem.includes(item))
      return dayOffType[key]
    }),
    legend: {
      show: true,
      data: Object.keys(subData).filter(item => item != 'dataGroupId'),
      formatter: (params) => params,
    },
    xAxis: {
      data: Object.keys(subData).filter(item => item != 'dataGroupId'),
      axisLabel: {
        formatter: (params) => params,
      }
    },
    yAxis: {},
    series: seriesData,
    graphic: [
      {
        type: 'text',
        left: '15%',
        top: 20,
        style: {
          fill: 'blue',
          text: '< 返回',
          fontSize: 14
        },
        onclick: function () {
          myChart.clear();
          myChart.setOption(options1);
          pageData.pageLevel = 1
        }
      }
    ]
  }
}

//生成表格3的数据
const genTable3Data = (subData, {groupId1, groupId2}) => {
  console.log("subData==", subData)
  pageData.pageLevelPre = pageData.pageLevel
  pageData.pageLevel = 3
  pageData.tableHeader3 = [groupId2]
  pageData.tableHeader3.unshift("序号", "月份", "天", "时间段", "员工编号")
  pageData.tableData3 = subData.data.map((subItem, index) => {
    subItem["序号"] = index + 1
    subItem["天"] = groupId1
    subItem["时间段"] = subItem[`${groupId1}_1`]  //1日_1
    subItem[groupId2] = subItem['员工姓名']
    return subItem
  })
}

//生成图表3详情的配置项
const genChartOptions3 = ({subData, eventData}) => {
  let {groupId1, groupId2} = eventData
  let dayOffTypeList = Object.keys(dayOffType)
  return {
    title: {
      text: `${props.parentPageData.monthValue}月${groupId1}_${groupId2}_数据`
    },
    color: [groupId2].filter(item => item != 'dataGroupId').map(item => {
      let key = dayOffTypeList.find(dayItem => dayItem.includes(item))
      return dayOffType[key]
    }),
    legend: {
      show: true,
      data: [groupId2],
      formatter: (params) => params,
    },
    xAxis: {
      data: [groupId2],
      axisLabel: {
        formatter: (params) => params,
      }
    },
    yAxis: {},
    series: [
      {
        name: groupId2,
        data: [subData.value],
        type: 'bar',
        barWidth: '50',
        label: {
          show: true,
          fontSize: 10,
          formatter: (params) => params.value ? params.value : '',
        },
      }
    ],
    graphic: [
      {
        type: 'text',
        left: '15%',
        top: 20,
        style: {
          fill: 'blue',
          text: '<< 返回',
          fontSize: 14
        },
        onclick: function () {
          pageData.myChart.clear();
          pageData.myChart.setOption(pageData.pageLevelPre == 1 ? pageData.options1 : pageData.options2);
          pageData.pageLevel = pageData.pageLevelPre
        }
      }
    ]
  }
}

//设置表格
const initECharts = () => {
  let {xAxisData, totalSeries, chartSeriesData, seriesData} = initChartData()
  // 基于准备好的dom，初始化echarts实例
  let myChart = echarts.init(document.getElementById('mainCharts'));
  pageData.myChart = myChart
  pageData.chartSeriesData = chartSeriesData
  // 绘制图表

  let options1 = genChartOptions1({xAxisData, totalSeries, seriesData})
  pageData.options1 = options1
  myChart.setOption(options1);

  myChart.on('click', function (event) {
    if (event.data) {//groupId- 1日 | 1/出勤
      let subData = chartSeriesData.find(item => item.dataGroupId === event.data.groupId1)
      if (!subData) {
        return;
      }
      let tableOptions = {}
      console.log("subData==", subData)
      //三级页面
      if (pageData.pageLevel == 2 && event.data.groupId2) {
        subData = subData[event.data.groupId2]
        genTable3Data(subData, event.data)
        tableOptions = genChartOptions3({subData, myChart, options1, eventData: event.data})
      } else {
        //二级页面
        genTable2Data(subData)
        tableOptions = genChartOptions2({subData, myChart, options1})
        pageData.options2 = tableOptions
      }
      console.log("tableOptions==", tableOptions)
      myChart.clear();
      myChart.setOption(tableOptions);
    }
  });
  window.addEventListener('resize', function () {
    myChart.resize();
  });
}

//初始化
onMounted(() => {
  initECharts()
})
</script>


<style scoped>

</style>